﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace HDJ.Framework.Core
{
    /// <summary>
    /// 将数据保存在沙河路径GameSaveData文件夹下
    /// </summary>
    public static class SaveDataManager
    {
        public static T GetData<T>(string fileName,string key,T defaultValue)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(key))
            {
                Debug.LogError("不能为空！  fileName :" + fileName + " key:" + key);
                return defaultValue;
            }
            Dictionary<string, string> dir = GetDirData(fileName);
            if (dir == null || !dir.ContainsKey(key))
                return defaultValue;

            string temp = dir[key];

            return JsonUtils.FromJson<T>(temp);
        }

        public static void SaveData(string fileName, string key,object data)
        {
            if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(key))
            {
                Debug.LogError("不能为空！  fileName :" + fileName + " key:" + key);
                return ;
            }
            string json = JsonUtils.ToJson(data);

            Dictionary<string, string> dir = GetDirData(fileName);
            if (dir == null )
            {
                dir = new Dictionary<string, string>();
                dir.Add(key, json);
            }
            else if (dir.ContainsKey(key))
            {
                dir[key] = json;
            }
            else if (!dir.ContainsKey(key))
            {
                dir.Add(key, json);
            }
            string path = GetSavePath(fileName);
            FileUtils.CreateTextFile(path, JsonUtils.ToJson(dir));
        }
        private static string GetSavePath(string fileName)
        {
            return Application.persistentDataPath + "/SaveData/" + fileName + ".txt";
        }
        private static Dictionary<string,string> GetDirData(string fileName)
        {
            string path = GetSavePath(fileName);
            string data=  FileUtils.LoadTextFileByPath(path);
            if (string.IsNullOrEmpty(data))
                return null;

            return JsonUtils.FromJson<Dictionary<string, string>>(data);
        }
    }
}
